package system

import (
	"context"
	"slices"
	"strconv"

	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListUserLogic struct {
	logx.Logger
	ctx       context.Context
	svcCtx    *svc.ServiceContext
	menuModel model.SysMenuModel
	deptModel model.SysDeptModel
	userModel model.SysUserModel
}

func NewListUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListUserLogic {
	return &ListUserLogic{
		Logger:    logx.WithContext(ctx),
		ctx:       ctx,
		svcCtx:    svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
		deptModel: model.NewSysDeptModel(svcCtx.Orm),
		userModel: model.NewSysUserModel(svcCtx.Orm),
	}
}

func (l *ListUserLogic) ListUser(req *types.ListUserRequest) (resp *types.CommonResponse, err error) {
	// 需要进行datascope
	err = auth.HasPermission(l.menuModel, l.ctx, "system:user:list")
	if err != nil {
		return nil, errorx.Unauthorized
	}
	authinfo, err := auth.GetAuth(l.ctx)
	if err != nil {
		return nil, errorx.AuthNoFound
	}
	roles, _ := auth.GetRoles(l.ctx)
	deptId, err := strconv.Atoi(authinfo.DeptId)
	if err != nil {
		return nil, errorx.TypeTransError
	}
	transDeptId := int64(deptId)
	deptIds := make([]*int64, 0)
	isAdmin,_ := auth.IsAdmin(l.ctx)
	if len(req.DeptId) > 0 {
		if isAdmin {
			deptIds = append(deptIds, &transDeptId)
		}else {
			depts, err := getDepts(l.ctx, int64(deptId), roles, l.deptModel, &types.ListDeptRequest{})
			if err != nil {
				return nil, errorx.Unauthorized
			}
			if len(req.DeptId) > 0 {
				isHas := slices.ContainsFunc(depts, func(d *types.Dept) bool {
					return d.DeptId == transDeptId
				})
				if !isHas {
					return nil, errorx.AuthNoFound
				}
				deptIds = append(deptIds, &transDeptId)
			} else {
				for _, val := range depts {
					deptIds = append(deptIds, &val.DeptId)
				}
			}
		}
	}
	userdtos, err := l.userModel.ListByCondition(l.ctx, nil, req, deptIds, isAdmin)
	if err != nil {
		return nil, errorx.NewBizError(500, err.Error())
	}
	uservos := make([]*types.User, 0)
	for _, user := range userdtos {
		uservos = append(uservos, &types.User{
			UserId:      user.UserId,
			DeptId:      strconv.Itoa(int(user.DeptId.Int64)),
			UserName:    user.UserName,
			NickName:    user.NickName,
			Avatar:      user.Avatar,
			Email:       user.Email,
			Phonenumber: user.Phonenumber,
			Sex:         user.Sex,
			Status:      user.Status,
			LoginDate:   user.LoginDate,
			UpdateTime:  user.UpdateTime,
			CreateTime:  user.CreateTime,
		})
	}
	count, err := l.userModel.CountByCondition(l.ctx, nil, req, deptIds, isAdmin)
	if err != nil {
		return nil, errorx.NewBizError(500, err.Error())
	}
	return &types.CommonResponse{
		Status: 200,
		Msg:    "查询成功",
		Data: &types.ListUserResponse{
			PageParamResponse: types.PageParamResponse{
				Total: *count,
				Size:  int64(len(uservos)),
			},
			Users: uservos,
		},
	}, nil
}
